import 'package:flutter/material.dart';
import 'package:znmm/UI/LoginPages/mag/user_info_manage.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/UI/utils/sharedpre_utils.dart';
import 'package:znmm/network/api_url.dart';
import 'package:znmm/network/dio_https.dart';
import 'package:znmm/network/notify_listener.dart';

import '../model/cart_model.dart';

class CnCartMag {
  static final CnCartMag _singleton = CnCartMag._internal();
  factory CnCartMag() {
    return _singleton;
  }

  CnCartMag._internal();

  void doSomething() {
    print("Doing something...");
  }

  void clearn() {
    _cartModelList.clear();
  }

  String totalPriceStr = "";

  final List<CnCartModel> _cartModelList = [];
  Future<List<CnCartModel>> getCartProductList() async {
    // if (_cartModelList.isEmpty && !UserInfoMag().bIsVisito) {
    //   // 从本地存储加载
    //   final loadedCartList = await loadCartModelList();
    //   // for (var item in loadedCartList) {
    //   //   print(
    //   //       "Name: ${item.name}, Quantity: ${item.iqty}, Price: ${item.fSiglePrice}");
    //   // }
    //   _cartModelList = loadedCartList;
    //   _computePrice();
    // }

    return _cartModelList;
  }

/*
  void addToCart(String imageStr, String nameStr, int iQty, double fSiglePrice,
      int iId, double totalPrice,
      {void Function()? callback}) {
    CnCartModel pMol = CnCartModel();
    pMol.featuredImage = imageStr.isNotEmpty
        ? imageStr
        : "https://pinshop.com/wp-content/uploads/woocommerce-placeholder-600x600.png";
    pMol.name = nameStr;
    pMol.iqty = iQty;
    pMol.fSiglePrice = fSiglePrice;
    pMol.id = iId;
    pMol.totalPrice = totalPrice;

    _cartModelList.add(pMol);
    _computePrice();
    NotifyCenter().postNotification(NotifyKey.cartProductKey);
    if (callback != null) {
      callback();
    }
  }

  void addAnRemQtNum(int iDatabaseId, int quantity, BuildContext context) {
    for (int iIndex = 0; iIndex < _cartModelList.length; iIndex++) {
      CnCartModel pMol = _cartModelList[iIndex];
      if (pMol.id == iDatabaseId) {
        int iQty = pMol.iqty + quantity;

        if (iQty == 0) {
          removeCart(context, pMol);
        } else {
          pMol.iqty = iQty;
          double totalPrice = pMol.fSiglePrice * iQty;
          pMol.totalPrice = totalPrice;

          //String formattedPrice = totalPrice.toStringAsFixed(2);

          _computePrice();
          NotifyCenter().postNotification(NotifyKey.cartProductKey);
        }

        break;
      }
    }
  }

  void removeCart(BuildContext context, CnCartModel pMol) {
    showDialog(
      context: context,
      builder: (context) => CustomDialog(
        //title: 'Confirmation',
        content: 'Remove from your cart?',
        onConfirm: () {
          // 这里处理确认按钮的逻辑
          print('Confirmed');
          _cartModelList.remove(pMol);
          _computePrice();
          NotifyCenter().postNotification(NotifyKey.cartProductKey);
        },
      ),
    );
  }
*/
  void _computePrice() {
    double totalPrice = 0;
    for (int iIndex = 0; iIndex < _cartModelList.length; iIndex++) {
      CnCartModel pMol = _cartModelList[iIndex];

      totalPrice += pMol.totalPrice;
    }

    String formattedPrice = totalPrice.toStringAsFixed(2);

    totalPriceStr = "\$$formattedPrice";
  }

  // 保存到本地存储
  //await saveCartModelList(cartList);
  Future<void> saveCartModelList() async {
    if (_cartModelList.isNotEmpty && !UserInfoMag().bIsVisito) {
      final jsonList = _cartModelList.map((item) => item.toJson()).toList();

      String carListKey = SharedKey.strCartListKey + UserInfoMag().user_id;

      await SharedPrefUtil().setJsonData(carListKey, {'cart': jsonList});

      MyGlobal.showInfo("save success");
    } else {
      MyGlobal.showInfo("Shopping cart is empty");
    }
  }

  //本地读取数据
  Future<List<CnCartModel>> loadCartModelList() async {
    String carListKey = SharedKey.strCartListKey + UserInfoMag().user_id;
    final jsonData = SharedPrefUtil().getJsonData(carListKey);
    if (jsonData.isNotEmpty && jsonData['cart'] != null) {
      return (jsonData['cart'] as List)
          .map((item) => CnCartModel.fromJson(item))
          .toList();
    }
    return [];
  }

  //1.网络-------------获取购物车数据 网络
  // final List<CnCartModel> _cartItems = [];
  // List<CnCartModel> getCartItemList() => _cartItems;

  void reqCartData({void Function()? callback}) {
    DioHttps dioUtil = DioHttps.instance!;
    dioUtil
        .request<dynamic>(
      APIUrl.gCartUrl,
      //bIsShowLoading: false,
      bIsShowResponse: true,
      bIsShowRequest: true,
      method: DioMethod.get,
    )
        .then((response) {
      // 处理响应数据
      print("response:$response");
      if (response == null || response is String) {
        print("response:$response");
        _cartModelList.clear();
        _computePrice();
        NotifyCenter().postNotification(NotifyKey.cartProductKey);
        if (callback != null) {
          callback();
        }
        return;
      }

      // 通过 `for` 循环迭代处理数据
      _cartModelList.clear();
      for (var entry in response.entries) {
        final cartItem = CnCartModel.fromJson2(entry.value);
        _cartModelList.add(cartItem);
      }

      // 打印解析后的数据
      for (var cartItem in _cartModelList) {
        print(cartItem.name); // 输出: HPT034 - C13, HPT034 - C11
      }
      _computePrice();
      NotifyCenter().postNotification(NotifyKey.cartProductKey);
      if (callback != null) {
        callback();
      }
    });
  }

  // 2.网络------------增加/减少/删除-购物车中的数量
  void reqIncrementQtNum(
      {required String itemKey,
      required int quantity,
      void Function()? callback}) {
    String strUrl = "${APIUrl.covattVeCartUrl}/$itemKey";
    DioHttps dioUtil = DioHttps.instance!;
    dioUtil
        .request<dynamic>(
      strUrl,
      method: quantity > 0 ? DioMethod.post : DioMethod.delete,
      data: quantity > 0 ? {"quantity": quantity} : null,
    )
        .then((response) {
      debugPrint("add=======>$response");

      reqCartData();
    });
  }
}
